<template>
  <ContentWrap title="创建审批单">
    <el-form :model="formData" :rules="formRules" ref="formRef">
      <el-descriptions :column="1" class="w-full" border>
        <el-descriptions-item label="业务名称">
          <el-form-item prop="name" class="!mb-0">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="业务类型">
          <el-form-item prop="type" class="!mb-0">
            <el-radio-group v-model="formData.type">
              <el-radio :label="1">VOS点呼/群呼主叫加白</el-radio>
              <el-radio :label="2">双向回拨号码加白</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="选择归属地">
          <el-form-item prop="locationId" class="!mb-0">
            <el-cascader
              v-model="formData.locationId"
              :options="locationList"
              :props="{ label: 'name', value: 'id' }"
              :show-all-levels="false"
              @change="handleChange"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="选择话术">
          <el-form-item prop="speechId" class="!mb-0">
            <el-select v-model="formData.speechId" placeholder="选择话术">
              <el-option
                v-for="item in speechList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
            <span class="ml-10px">{{ speechView }}</span>
            <span @click="openSpeechForm('create')" class="ml-10px color-#0052cc cursor-pointer"
              >添加话术</span
            >
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="选择坐席">
          <el-tag v-for="item in selectedAgent" :key="item.id" class="mr-6px mb-4px">{{
            item.agentNumber
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-table :data="agentList" :stripe="true" border :show-overflow-tooltip="true">
            <el-table-column label="坐席工号" align="center" prop="agentNumber" />
            <el-table-column label="双呼主叫手机号" align="center" prop="telephone" width="150" />
            <el-table-column label="真实姓名" align="center" prop="realName" width="220">
              <template #default="scope">
                <div v-if="scope.row.realName != null">
                  {{ scope.row.realName }}
                </div>
                <div v-if="scope.row.realName == null">
                  <el-input
                    maxlength="10"
                    clearable
                    v-if="scope.row.isShowRealNameInput == true"
                    v-model.trim="scope.row.realNameValue"
                    class="w-120px!"
                    placeholder="请输入真实姓名"
                  />
                  <el-icon
                    v-if="!scope.row.isShowRealNameInput"
                    @click="scope.row.isShowRealNameInput = !scope.row.isShowRealNameInput"
                    :size="12"
                    color="green"
                    class="cursor-pointer"
                  >
                    <Plus />
                  </el-icon>
                  <el-icon
                    v-if="scope.row.isShowRealNameInput"
                    @click="handleSaveName(scope.row.realNameValue, scope.row, 'name')"
                    :size="12"
                    color="green"
                    class="cursor-pointer px-10px"
                  >
                    <Select />
                  </el-icon>
                  <el-icon
                    v-if="scope.row.isShowRealNameInput"
                    @click="scope.row.isShowRealNameInput = !scope.row.isShowRealNameInput"
                    :size="12"
                    color="green"
                    class="cursor-pointer pl-0px"
                  >
                    <CloseBold />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="身份证号" align="center" prop="idNumber" width="280">
              <template #default="scope">
                <div v-if="scope.row.idNumber != null">
                  {{ scope.row.idNumber }}
                </div>
                <div v-if="scope.row.idNumber == null">
                  <el-input
                    maxlength="18"
                    clearable
                    v-if="scope.row.isShowIdNumberInput == true"
                    v-model.trim="scope.row.idNumberValue"
                    class="w-200px!"
                    placeholder="请输入身份证号"
                  />
                  <el-icon
                    v-if="!scope.row.isShowIdNumberInput"
                    @click="scope.row.isShowIdNumberInput = !scope.row.isShowIdNumberInput"
                    :size="12"
                    color="green"
                    class="cursor-pointer"
                  >
                    <Plus />
                  </el-icon>
                  <el-icon
                    v-if="scope.row.isShowIdNumberInput"
                    @click="handleSaveName(scope.row.idNumberValue, scope.row, 'idNumber')"
                    :size="12"
                    color="green"
                    class="cursor-pointer px-10px"
                  >
                    <Select />
                  </el-icon>
                  <el-icon
                    v-if="scope.row.isShowIdNumberInput"
                    @click="scope.row.isShowIdNumberInput = !scope.row.isShowIdNumberInput"
                    :size="12"
                    color="green"
                    class="cursor-pointer px-0px"
                  >
                    <CloseBold />
                  </el-icon>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="点呼主叫加白" align="center" prop="sipCallAuditStatus">
              <template #default="scope">
                <div>
                  <el-tag
                    v-if="auditStatusMap[scope.row.sipCallAuditStatus]"
                    :type="auditStatusMap[scope.row.sipCallAuditStatus].type"
                    >{{ auditStatusMap[scope.row.sipCallAuditStatus].text }}</el-tag
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="双向回拨加白" align="center" prop="doubleCallAuditStatus">
              <template #default="scope">
                <div>
                  <el-tag
                    v-if="auditStatusMap[scope.row.doubleCallAuditStatus]"
                    :type="auditStatusMap[scope.row.doubleCallAuditStatus].type"
                    >{{ auditStatusMap[scope.row.doubleCallAuditStatus].text }}</el-tag
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="负责人" align="center" prop="ownerUsername" />

            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-tag type="info" v-if="scope.row.status == 0">未启用</el-tag>
                <el-tag type="success" v-if="scope.row.status == 1">已启用</el-tag>
                <el-tag type="danger" v-if="scope.row.status == 9">已过期</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            />

            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button
                  v-if="!isSelected(scope.row)"
                  link
                  type="primary"
                  @click="select(scope.row)"
                  :disabled="!canAgentSelect(scope.row)"
                >
                  选择
                </el-button>
                <el-button v-else link type="danger" @click="unSelect(scope.row)"> 取消 </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="agentQueryForm.pageNo"
            v-model:limit="agentQueryForm.pageSize"
            @pagination="getAgentPage"
          />
        </el-descriptions-item>

        <el-descriptions-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="returnBack">返回</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
  </ContentWrap>

  <SpeechForm ref="speechFormRef" @success="getSpeechList" />
</template>

<script setup>
import * as SpeechApi from '@/api/call/speech'
import * as LocationApi from '@/api/call/location'
import * as WhiteAuditApi from '@/api/call/whiteaudit'
import * as AreaApi from '@/api/system/area'
import * as AgentApi from '@/api/call/agent'
import { dateFormatter } from '@/utils/formatTime'
import { Plus, Select, CloseBold } from '@element-plus/icons-vue'
import SpeechForm from '../speech/SpeechForm.vue'

const message = useMessage()

const handleSaveName = async (val, row, field) => {
  if (field == 'name') {
    if (val) {
      row.realName = val
    } else {
      message.error('请输入真实姓名')
      return
    }
  }
  if (field == 'idNumber') {
    let idReg =
      /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
    if (idReg.test(val) != true) {
      message.error('请输入有效的身份证号码！')
      return
    } else {
      row.idNumber = val
    }
  }
  await AgentApi.updateAgent(row)
  message.success(t('common.updateSuccess'))
  row.isShowRealNameInput = false
}

// 表单
const formData = ref({
  type: 1,
  name: '',
  speechId: '',
  locationId: '',
  agentList: []
})
const formRules = reactive({
  name: [
    {
      required: true,
      message: '业务名称不能为空',
      trigger: 'blur'
    }
  ],
  speechId: [
    {
      required: true,
      message: '话术不能为空',
      trigger: 'change'
    }
  ],
  locationId: [
    {
      required: true,
      message: '归属地不能为空',
      trigger: 'change'
    }
  ]
})

// 归属地
const locationList = ref([])
const getLocationList = async () => {
  const data = await AreaApi.getAreaTree()
  locationList.value = data.map((i) => {
    i.children = i.children.map((t) => {
      t.children = []
      return t
    })
    return i
  })
}

const handleChange = (value) => {
  formData.value.locationId = value[1]
}

// 话术
const speechList = ref([])
const getSpeechList = async () => {
  speechList.value = await SpeechApi.getSpeechList()
}
const speechFormRef = ref()
const openSpeechForm = (type) => {
  speechFormRef.value.open(type)
}
// 话术预览
const speechView = computed(() => {
  if (formData.value.speechId) {
    return speechList.value.find((v) => v.id == formData.value.speechId)?.content ?? ''
  }
})

const auditStatusMap = {
  0: { type: 'info', text: '待审批' },
  1: { type: 'success', text: '已加白' },
  2: { type: 'danger', text: '不通过' }
}
// 坐席
const total = ref(0)
const agentList = ref([])
const agentQueryForm = reactive({
  pageNo: 1,
  pageSize: 10,
  agentNumber: '',
  sipCallAuditStatus: '',
  doubleCallAuditStatus: ''
})
const getAgentPage = async () => {
  const data = await AgentApi.getAgentPage(agentQueryForm)
  agentList.value = data.list
  total.value = data.total
}
const canAgentSelect = (item) => {
  if (!item.realName || !item.idNumber) {
    return false
  }
  if (formData.value.type == 1 && item.sipCallAuditStatus == 1) {
    // 检查vos主叫是否已经加白
    return false
  }
  if (formData.value.type == 2 && item.doubleCallAuditStatus == 1) {
    // 检查双向回拨是否已经加白
    return false
  }
  return true
}
// 已选坐席
const selectedAgent = ref([])
const select = (item) => {
  selectedAgent.value.push(item)
  formData.value.agentList = selectedAgent.value.map((v) => v.id)
}
// 取消选择
const unSelect = (item) => {
  let index = selectedAgent.value.findIndex((v) => v.id == item.id)
  selectedAgent.value.splice(index, 1)
  formData.value.agentList = selectedAgent.value.map((v) => v.id)
}
// 判断是否已选
const isSelected = (item) => {
  return selectedAgent.value.findIndex((v) => v.id == item.id) >= 0
}

// 操作栏
const { replace } = useRouter()
const formRef = ref()
const returnBack = () => {
  replace({ path: '/call/white-audit' })
}
const submitForm = async () => {
  if (selectedAgent.value.length == 0) {
    message.error('尚未选择坐席')
    return
  }
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  const data = await WhiteAuditApi.createWhiteAudit(formData.value)
  message.success('提交成功')
  setTimeout(() => {
    returnBack()
  }, 1500)
}

onMounted(() => {
  getLocationList()
  getSpeechList()
  getAgentPage()
})
</script>
